﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using ZLCMS.Business;
using System.Text;
using NHibernate.Criterion;
using ZLCMS.Data.Common;
using NHibernate;
using ZLCMS.Data.Model;
using ZLCMS.Business.Config;
using ZLCMS.Business.ShopCart;
using ZLCMS.Business.Util;
using System.Collections.Generic;
using ZLCMS.Business.Shop.Commands.Order;
using DotNet.Common.NHibernateUtil;

namespace ZLCMS.Web.ShopCart
{
    public partial class ShoppingCartConfirm : System.Web.UI.Page
    {
        protected MemberInfo _memberDb;
        protected decimal _totalPrice = 0; //合计
        protected decimal _totalWeight = 0;//商品重量
        protected int _totalCount = 0; //商品数量

        protected decimal _shippingPrice //运费
        {
            get
            {
                return 0;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _memberDb = Master.LoadMember();

            //初始化全局变量值
            InitializeGlobalValue();

            //初始化控件值
            InitializeContent();
        }

        private void InitializeGlobalValue()
        {
            _memberDb = Master.LoadMember();
        }

        private void InitializeContent()
        {
            //不放在if (!IsPostBack)中，为了在提交时再次确认数据，并且为了初始化 _totalPrice 等值
            List<ShopCartCookiesInfo> productList = new ShoppingCartKit().ProductList;

            if (productList == null)
            {
                Response.Write("<script language=\"javascript\" type=\"text/javascript\">alert('您的购物车还没有商品，请先选择商品。');window.location.href='/ShopCart/ShoppingCart.aspx'</script>");
            }

            rp_productlist.DataSource = productList;
            rp_productlist.DataBind();

            if (!IsPostBack)
            {

                //TODO 由地址列表中获取
                //txtRName.Text = _member.Shname;
                //txtRAddress.Text = _member.Shaddress;
                //txtRPhone.Text = _member.Shtel;
                //txtRPostalcode.Text = _member.Shcode;

                //cdd_province.SelectedValue = _member.Sheng;
                //cdd_city.SelectedValue = _member.Shi;

                BindShippingData();
                BindPaymentData();
                BindAddressData();
            }
        }

        private void BindAddressData()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                IList<MemberAddress> addressList=session.CreateCriteria<MemberAddress>().Add(Expression.Eq("MemberAccount", _memberDb.AccountId)).AddOrder(Order.Desc("Status")).List<MemberAddress>();
                if (addressList.Count > 0)
                {
                    foreach (MemberAddress item in addressList)
                    {
                        rbl_address.Items.Add(new ListItem(item.Receiver + "，" + ParamKit.GetValue("Province", item.Province, "") + "," + ParamKit.GetValue("City", item.City, "") + "," + item.Address + "," + item.Mobile, item.Id.ToString()));
                    }
                    rbl_address.Items[0].Selected = true;
                }
            }
        }

        private void BindPaymentData()
        {
            
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                IList<ShopPaymentInfo> paymentList = session.CreateCriteria<ShopPaymentInfo>().List<ShopPaymentInfo>();
                if (paymentList.Count > 0)
                {
                    foreach (ShopPaymentInfo item in paymentList)
                    {
                        rbl_payment.Items.Add(new ListItem(item.PaymentName + "(" + item.Description + ")", item.Id.ToString()));
                    }
                    rbl_payment.Items[0].Selected = true;
                }
            }
        }

        private void BindShippingData()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                IList<ShopShippingInfo> shippingList = session.CreateCriteria<ShopShippingInfo>().List<ShopShippingInfo>();
                if (shippingList.Count > 0)
                {
                    foreach (ShopShippingInfo item in shippingList)
                    {
                        rbl_shipping.Items.Add(new ListItem(item.ShippingName + "，计算公式：[" + item.Expression + "]", item.Id.ToString()));
                    }
                    rbl_shipping.Items[0].Selected = true;
                }
            }
        }

        protected void rp_productlist_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                ShopCartCookiesInfo productCartItem = (ShopCartCookiesInfo)e.Item.DataItem;
                using (ISession session = SessionFactoryHelper.CreateSession())
                {
                    ShopProductInfo product = session.Get<ShopProductInfo>(productCartItem.ProductId);
                    if (product != null)
                    {
                        (e.Item.FindControl("img_product") as Image).ImageUrl = FileKit.FirstFilePath(product.ThumbnailImg);
                        (e.Item.FindControl("lb_productname") as Label).Text = product.ProductName;
                        (e.Item.FindControl("lb_price") as Label).Text = product.SalePrice.ToString("0.00");
                        (e.Item.FindControl("lb_totalprice") as Label).Text = (product.SalePrice * productCartItem.Quantity).ToString("0.00");

                        _totalPrice += product.SalePrice * productCartItem.Quantity;
                        _totalWeight += product.Weight * productCartItem.Quantity;
                        _totalCount += productCartItem.Quantity;
                    }
                }
            }
        }

        protected void tb_commit_Click(object sender, EventArgs e)
        {
            ShopOrderInfo ordersDB = new ShopOrderInfo();

            //CreateOrderResult cmdResult;
            try
            {
                // 获取地址信息
                MemberAddress mbAddressDb;

                using (ISession session = SessionFactoryHelper.CreateSession())
                {
                    mbAddressDb = session.Get<MemberAddress>(int.Parse(rbl_address.SelectedValue));
                }

                if (mbAddressDb == null)
                {
                    throw new Exception("请选择收货人信息。");
                }
                
                CreateOrderParameter cmdParam = new CreateOrderParameter();

                cmdParam.UserCode = _memberDb.AccountId;

                cmdParam.ReceiverName = mbAddressDb.Receiver;
                cmdParam.ReceiverPhone = mbAddressDb.Phone;
                cmdParam.ReceiverEmail = "";//不需要EMAIL，使用注册会员的邮箱即可
                cmdParam.ReceiverAddress = ParamKit.GetValue("Province", mbAddressDb.Province, "") + "," + ParamKit.GetValue("City", mbAddressDb.City, "") + "," + mbAddressDb.Address;

                cmdParam.Remark = txtRemark.Text;

                cmdParam.TotalPrice = _totalPrice + _shippingPrice;
                cmdParam.ProductPrice = _totalPrice; 
                cmdParam.ItemsPrice = 0;
                cmdParam.Discount = 100;
                cmdParam.ShipPrice = _shippingPrice;
                cmdParam.UseAdvancePayment = 0;
                cmdParam.UseScore = 0;
                cmdParam.UseCoins = 0;
                cmdParam.RealPrice =decimal.Parse(ordersDB.TotalPrice.ToString()) - decimal.Parse(ordersDB.UseAdvancePayment.ToString());//实际支付金额，总价 - 预付款
                cmdParam.PaymentType = rbl_payment.SelectedValue;
                cmdParam.ShippingType = rbl_shipping.SelectedValue;

                cmdParam.Score = 0;//赠送积分
                cmdParam.Coins = 0;//赠送点数
                cmdParam.Weight = _totalWeight;
                cmdParam.Quantity = _totalCount;

                cmdParam.NeedInvoice = "0";// 是否需要发票
                cmdParam.InvoiceHead = "";
                cmdParam.InvoiceInfo = "";              

                cmdParam.OrderType = "1";//订单类型，1为普通，2为团购

                // 获取订单内产品信息
                List<ProductInCreateOrder> cmdProductList = new List<ProductInCreateOrder>();

                List<ShopCartCookiesInfo> productList = new ShoppingCartKit().ProductList;

                if (productList == null)
                {
                    throw new Exception("您的购物车还没有商品，请先选择商品。");
                }

                foreach (ShopCartCookiesInfo item in productList)
                {
                    ProductInCreateOrder productParam = new ProductInCreateOrder();

                    productParam.ProductNo = item.ProductId.ToString();
                    productParam.Items =item.Items;
                    productParam.Quantity = item.Quantity;
                    productParam.Remark = "";

                    cmdProductList.Add(productParam);
                }
                cmdParam.ProductList = cmdProductList;

                CreateOrderCommand cmd = new CreateOrderCommand();

                DotNet.Common.Command.CommandResult cmdResult = cmd.Execute(cmdParam);

                if (cmdResult.Error)
                {
                    throw new Exception("提交订单错误，错误代码：" + cmdResult.ErrorCode);
                }
                else
                {
                    Response.Write("<script language=\"javascript\" type=\"text/javascript\">window.location.href='/ShopCart/ShoppingCartComfirmSuccess.aspx?o=" + ((CreateOrderResult)cmdResult).OrderNo + "'</script>");
                }
            }
            catch (System.Exception ex)
            {
                Response.Write("<script language=\"javascript\" type=\"text/javascript\">alert('" + ex.Message + "');window.location.href='/ShopCart/ShoppingCartConfirm.aspx'</script>");

                return;
            }

            new ShoppingCartKit().ClearProduct();
        }

    }
}
